package com.choosefine.base.shixiaobao.common.utils;

import java.io.File;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtils {

	/**
	 * @param obj
	 * @return 如果obj为空或者为''返回true，否则返回false
	 * @Description 判断对象是否为空
	 * @author liaozhanggen-c
	 */
	public static boolean isEmpty(Object obj) {
		if (obj == null) {
			return true;
		}
		// 字符串类型
		else if (obj instanceof String) {
			return obj.toString().trim().length() <= 0 ? true : false;
		}
		// list类型
		else if (obj instanceof List<?>) {
			return ((List<?>) obj).size() <= 0 ? true : false;
		}
		// 数组类型
		else if (obj.getClass().isArray()) {
			return Array.getLength(obj) <= 0 ? true : false;
		}
		// 集合类型
		else if (obj instanceof Collection) {
			return ((Collection<?>) obj).size() <= 0 ? true : false;
		}
		// map类型
		else if (obj instanceof Map) {
			return ((Map<?, ?>) obj).size() <= 0 ? true : false;
		}
		// 文件类型
		else if (obj instanceof File) {
			return ((File) obj).exists();
		}
		return false;
	}

	/**
	 * @param obj
	 * @return 如果obj不为空并且不为''返回true，否则返回false
	 * @Description 判断对象是否不为空
	 * @author mengLei
	 * @date 2015-2-4 上午11:58:51
	 */
	public static boolean isNotEmpty(Object obj) {
		return !isEmpty(obj);
	}

	/**
	 * @param obj
	 * @return 如果字符串为null、''或者"null"时返回true，否则返回false
	 * @Description 判断字符串是否为null或者''或者为"null"
	 * @author liaozhanggen-c
	 */
	public static boolean isNullStr(String obj) {
		if (isEmpty(obj) || "null".equals(obj.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * @param obj
	 * @return
	 * @Description 判断字符串是否不为空并且不为"null"
	 * @author liaozhanggen-c
	 */
	public static boolean isNotStrNull(String obj) {
		if (isNotEmpty(obj) && !"null".equals(obj.trim())) {
			return true;
		}
		return false;
	}

	/**
	 * @param str
	 * @return
	 * @Description 首字母小写
	 * @author liaozhanggen-c
	 */
	public static String firstLetter2Lower(String str) {
		if (isNotEmpty(str)) {
			return str.substring(0, 1).toLowerCase() + str.substring(1);
		}
		return str;
	}

	/**
	 * @param str
	 * @return
	 * @Description 首字母大写
	 * @author liaozhanggen-c
	 */
	public static String firstLetter2UpperCase(String str) {
		if (isNotEmpty(str)) {
			return str.substring(0, 1).toUpperCase() + str.substring(1);
		}
		return str;
	}

	/**
	 * @param str    指定字符串
	 * @param length 自定的字符串长度
	 * @param symbol 补填的字符串
	 * @return
	 * @Description 自动在str后补充(length-str.length())个symbol<br>
	 * 比如：str="11" , length = 5 , symbol="0" , 最后返回 : 11000
	 * @author liaozhanggen-c
	 */
	public static String appendCharacterForLast(String str, int length, String symbol) {
		int strLen = str.length();
		if (strLen < length) {
			while (strLen < length) {
				StringBuffer sb = new StringBuffer();
				sb.append(str).append(symbol);// 左补0
				str = sb.toString();
				strLen = str.length();
			}
		}
		return str;
	}

	/**
	 * @param isFormt 是否需要格式化。<br>
	 *                此处格式化指：是否将uuid中的"-"去掉（true:格式化,false:不需要格式化）
	 * @return
	 * @Description 获取uuid
	 * @author liaozhanggen-c
	 */
	public static String getUUID(boolean isFormt) {
		String uuid = UUID.randomUUID().toString();
		if (isFormt) {
			uuid = uuid.replaceAll("-", "");
		}
		return uuid;
	}

	/**
	 * @param str : xx_xx
	 * @return
	 * @Description 首字母大写
	 * @author liaozhanggen
	 */
	public static String initialtoUpper(String str) {
		if (null != str)
			return str.substring(0, 1).toUpperCase() + str.substring(1);
		else
			return str;
	}

	/**
	 * @param str : xx_xx
	 * @return
	 * @Description 首字母大写
	 * @author liaozhanggen
	 */
	public static String splitAndtoUpper(String str, String splitStr) {
		String[] temps = str.split(splitStr);
		str = temps[0];
		for (int i = 1; i < temps.length; i++) {
			str += initialtoUpper(temps[i]);
		}
		return str;
	}

	/**
	 * @param str : xx_xx
	 * @return
	 * @Description 首字母大写
	 * @author liaozhanggen
	 */
	public static String splitAndInitialtoUpper(String str, String splitStr) {
		str = splitAndtoUpper(str, splitStr);
		return initialtoUpper(str);
	}

	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|\n");
			Matcher m = p.matcher(str);
			dest = m.replaceAll("");
		}
		return dest;
	}


	public static int getBlankNumber(String s, int index) {
		if (index < s.length()) {
			if (s.charAt(index) == ' ') {
				return getBlankNumber(s, index + 1) + 1;
			} else {
				return 0;
			}
		} else {
			return 0;
		}
	}


	public static String mergeBlank(String s) {
		int numberBlank = 0;
		String a1;//字符串的第一部分
		String a2;//字符串的第二部分
		for (int index = 0; index < s.length(); index++) {//循环整个字符串，判断是否有连续空格
			numberBlank = getBlankNumber(s, index);
			if (numberBlank >= 2) {//根据连续空格的个数以及当前的位置，截取字符串
				a1 = s.substring(0, index);
				a2 = s.substring(index + numberBlank - 1, s.length());
				s = a1 + a2;//合并字符串
			}
		}
		return s;
	}

	public static String trim(String s) {
		if (s.charAt(0) == ' ') {
			s = s.substring(1, s.length());
		}
		if (s.charAt(s.length() - 1) == ' ') {
			s = s.substring(0, s.length() - 1);
		}
		return s;
	}

	public static String replaceBankByArray(String str) {
		StringBuilder sbl = new StringBuilder("");
		String text = str.replaceAll("\n", " ");
		text = text.replaceAll(" ", " ");
		String[] textArray = text.split(" ");
		for (String temp : textArray) {
			temp = (temp.trim()).trim();
			if (!temp.equals(" ") && !temp.equals(" ") && !temp.equals("") && temp != null) {
				sbl.append(temp.trim());
				sbl.append(" ");
			}
		}
		String string = (sbl.toString()).trim();
		Pattern p = Pattern.compile(" {2,}");// 去除多余空格
		Matcher m = p.matcher(string);
		String second = m.replaceAll(" ");
		return second;

	}


//    public static void main(String[] args) {
////        System.out.println(StringUtil.replaceBlank("just    do it!"));
//        String stringInfo = "Madam,           I'm Adam";
//        System.out.println("待处理的字符串：" + stringInfo);
//
//        Pattern p = Pattern.compile("[.,\"\\?!:']");// 增加对应的标点
//        Matcher m = p.matcher(stringInfo);
//
//        String first = m.replaceAll(""); // 把英文标点符号替换成空，即去掉英文标点符号
//        System.out.println("去掉英文标点符号后的字符串：" + first);
//
//        p = Pattern.compile(" {2,}");// 去除多余空格
//        m = p.matcher(first);
//        String second = m.replaceAll(" ");
//        System.out.println("去掉多余空格后的字符串" + second);// second为最终输出的字符串
//
//        second = first.replace(" ", "");
//        System.out.println("去掉所有空格：" + second);
//    }


	public static Boolean isExcel(String fileName) {
		if (fileName != null && fileName != "") {
			//lastIndexOf如果没有搜索到则返回为-1
			if (fileName.lastIndexOf(".") != -1) {
				String fileType = (fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length())).toLowerCase();
				String[] suppotFile = new String[2];
				suppotFile[0] = "xlsx";
				suppotFile[1] = "xls";
				for (int i = 0; i < suppotFile.length; i++) {
					if (suppotFile[i].equals(fileType)) {
						return true;
					}
				}
				return false;
			} else {
				return false;
			}
		}
		return false;
	}

	/**
	 * 将目录进行截取
	 *
	 * @param dir
	 * @param format
	 * @return
	 */
	public static String excelRootCheck(String dir,String format){
		String uri = "";
		int index = dir.indexOf(format);
		if (index == -1) { //校验格式不存在
			return "";
		}
		uri = dir.substring(index);
		return uri;
	}

	/**
	 * 如果str为null，返回“”,否则返回str
	 *
	 * @param str
	 * @return
	 */
	public static String isNull(String str) {
		if (str == null) {
			return "";
		}
		return str;
	}

	public static String isNull(Object o) {
		if (o == null) {
			return "";
		}
		String str = "";
		if (o instanceof String) {
			str = (String) o;
		} else {
			str = o.toString();
		}
		return str;
	}

	/**
	 * 检查email是否是邮箱格式，返回true表示是，反之为否
	 *
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		email = isNull(email);
		Pattern regex = Pattern
				.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
		Matcher matcher = regex.matcher(email);
		boolean isMatched = matcher.matches();
		return isMatched;
	}

	/**
	 * 检查身份证的格式，返回true表示是，反之为否
	 *
	 * @param
	 * @return
	 */
	public static boolean isCard(String cardId) {
		cardId = isNull(cardId);
		// 身份证正则表达式(15位)
		Pattern isIDCard1 = Pattern
				.compile("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$");
		// 身份证正则表达式(18位)
		Pattern isIDCard2 = Pattern
				.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");
		Matcher matcher1 = isIDCard1.matcher(cardId);
		Matcher matcher2 = isIDCard2.matcher(cardId);
		boolean isMatched = matcher1.matches() || matcher2.matches();
		return isMatched;
	}

	/**
	 * 判断字符串是否为整数
	 *
	 * @param str
	 * @return
	 */
	public static boolean isInteger(String str) {
		if (isEmpty(str)) {
			return false;
		}
		Pattern regex = Pattern.compile("\\d*");
		Matcher matcher = regex.matcher(str);
		boolean isMatched = matcher.matches();
		return isMatched;
	}

	/**
	 * 判断字符串是否为数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		if (isEmpty(str)) {
			return false;
		}
		Pattern regex = Pattern.compile("\\d*(.\\d*)?");
		Matcher matcher = regex.matcher(str);
		boolean isMatched = matcher.matches();
		return isMatched;
	}
	/*判断字符串是否为数字,支持逗号的判断 如1,2,3返回为true  如果传入为001,002也可以 sql可以识别 就当是1,2 yuxin3.17*/
	public static boolean isNumberYX(String str) {
		if (isEmpty(str)) {
			return false;
		}
		Pattern regex = Pattern.compile("([0-9]+[,]?)+");
		Matcher matcher = regex.matcher(str);
		boolean isMatched = matcher.matches();
		return isMatched;
	}

	/**
	 * 判断字符串是否为空
	 *
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		if (str == null || "".equals(str)) {
			return true;
		}
		return false;
	}

	public static boolean isNotEmpty(String str) {
		if (str != null && !"".equals(str)) {
			return true;
		}
		return false;
	}

	/**
	 * 首字母大写
	 *
	 * @param s
	 * @return
	 */
	public static String firstCharUpperCase(String s) {
		StringBuffer sb = new StringBuffer(s.substring(0, 1).toUpperCase());
		sb.append(s.substring(1, s.length()));
		return sb.toString();
	}

	public static String hideChar(String str, int len) {
		if (str == null)
			return null;
		char[] chars = str.toCharArray();
		for (int i = 1; i > chars.length - 1; i++) {
			if (i < len) {
				chars[i] = '*';
			}
		}
		str = new String(chars);
		return str;
	}

	public static String hideFirstChar(String str, int len) {
		if (str == null)
			return null;
		char[] chars = str.toCharArray();
		if (str.length() <= len) {
			for (int i = 0; i < chars.length; i++) {
				chars[i] = '*';
			}
		} else {
			for (int i = 0; i < 1; i++) {
				chars[i] = '*';
			}
		}
		str = new String(chars);
		return str;
	}

	public static String hideLastChar(String str, int len) {
		if (str == null)
			return null;
		char[] chars = str.toCharArray();
		if (str.length() <= len) {
			for (int i = 0; i < chars.length; i++) {
				chars[i] = '*';
			}
		} else {
			for (int i = chars.length - 1; i > chars.length - len - 1; i--) {
				chars[i] = '*';
			}
		}
		str = new String(chars);
		return str;
	}

	/**
	 *
	 * @return
	 */
	public static String format(String str, int len) {
		if (str == null)
			return "-";
		if (str.length() <= len) {
			int pushlen = len - str.length();
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < pushlen; i++) {
				sb.append("0");
			}
			sb.append(str);
			str = sb.toString();
		} else {
			String newStr = str.substring(0, len);
			str = newStr;
		}
		return str;
	}

	public static String contact(Object[] args) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < args.length; i++) {
			sb.append(args[i]);
			if (i < args.length - 1) {
				sb.append(",");
			}
		}
		return sb.toString();
	}

	/**
	 * 是否包含在以“，”隔开字符串内
	 *
	 * @param s
	 * @param type
	 * @return
	 */
	public static boolean isInSplit(String s, String type) {
		if (isNull(s).equals("")) {
			return false;
		}
		List<String> list = Arrays.asList(s.split(","));
		if (list.contains(type)) {
			return true;
		}
		return false;
	}

	public static boolean isBlank(String str) {
		return StringUtils.isNull(str).equals("");
	}

	public synchronized static String wyTradeNO(String date, String vmid,
												long userid, String type) {
		String s;
		Random rand = new Random((new Date()).getTime());
		int tmp = Math.abs(rand.nextInt());
		int retmp = tmp % (99999 - 10000 + 1) + 10000;
		s = date + vmid + type + String.valueOf(retmp);
		return s;
	}

	public static String array2Str(Object[] arr) {
		StringBuffer s = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			s.append(arr[i]);
			if (i < arr.length - 1) {
				s.append(",");
			}
		}
		return s.toString();
	}

	public static String array2Str(int[] arr) {
		StringBuffer s = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			s.append(arr[i]);
			if (i < arr.length - 1) {
				s.append(",");
			}
		}
		return s.toString();
	}

	public static int getStrHaveCheckStrNum(String str, String checkstr) {
		char[] ch = str.toCharArray();
		int count = 0;
		for (int i = ch.length - 1; i >= 0; i--) {
			if (checkstr.equals(String.valueOf(ch[i]))) {
				count++;
			} else {
				break;
			}
		}
		return count;
	}

	/**
	 * @author chenjian
	 * @param str
	 * @return
	 */
	public static boolean isNotBlank(String str) {
		if (str != null && !"".equals(str.trim())) {
			return true;
		}
		return false;
	}
	// public static void main(String[] args) {
	// System.out.println(StringUtils.isNumber("112"));
	// }
	/**
	 * @decription 校验民族，个人新增租户，限制汉字或英文，不允许数字与符号，非必填
	 * @param str
	 * @author Xiongdong
	 * @return
	 */
	public static boolean checkCnOrEn(String str){
		if(StringUtils.isBlank(str)){
			return true;
		}
		return Pattern.matches("^[a-zA-Z\\u4E00-\\u9FA5]+$", str);
	}


}
